<template>
	<div class="file-componets-container">
		<p class="title">{{ title }}</p>
		<hr class="hr" v-if="fileType !== 'agent-recorg' && fileType !== 'regional-screen'" />
		<div class="header-box">
			<el-button
				type="primary"
				:class="isDisable ? 'gray-btn' : 'download-btn'"
				:disabled="isDisable"
				@click="onClickDownload(fileType)"
				id="intro"
				v-if="fileType !== 'agent-recorg' && fileType !== 'regional-screen'"
				>下载
			</el-button>
			<el-input placeholder="请输入搜索内容" v-model="searchKeyWord" v-show="fileType === 'message' || fileType === 'business'">
				<el-button slot="append" icon="el-icon-search" @click="searchClick"></el-button>
			</el-input>
		</div>
		<div class="content">
			<!-- 视频区域 -->
			<template v-if="fileType === 'video' && getSystemRecordFiles.length !== 0">
				<!-- 系统录像 区域  -->
				<p class="system-video">系统录像</p>
				<div class="video-box" v-for="(item, index) in getSystemRecordFiles" :key="index">
					<MarkerVideo :option="item" :videoConfig="videoConfig" :fileType="fileType" />
				</div>
				<div class="videoFile-box" v-if="recordingConfig">
					<span class="title" v-if="recordingConfig.storageType === 'nas'">录像文件存储类型：nas(本地磁盘录制)</span>
					<span class="title" v-else-if="recordingConfig.storageType === 'ali'">录像文件存储类型：ali(阿里OSS)</span>
					<span class="title" v-else>录像文件存储类型：aws</span>
					<p sclass="paddingTop" v-if="recordingConfig.storageType === 'nas'">
						<span class="title">文件存储的nas盘地址:</span>
						<el-input placeholder="" :value="recordingConfig.nasBasePath" :disabled="true" class="paddingTop"> </el-input>
					</p>
					<p class="paddingTop" v-if="recordingConfig.notifyURL">
						<span class="title">通知的第三方服务URL地址:</span>
						<el-input placeholder="" :value="recordingConfig.notifyURL" :disabled="true" class="paddingTop"> </el-input>
					</p>
				</div>
			</template>
			<!--坐席录屏 区域  recorging  -->
			<template v-if="fileType === 'agent-recorg' && getAgentRecordFiles.length !== 0">
				<div class="agent-recorg-video">
					<div class="seat-recording-video-wrapper">
						<p class="recording-screen">坐席录屏</p>
						<div class="seat-recording-video" v-for="(item, index) in getAgentRecordFiles" :key="index">
							<MarkerVideo :option="item" :videoConfig="videoConfig" :fileType="fileType" />
						</div>
					</div>
				</div>
			</template>
			<!--区域录屏  regional-screen -->
			<template v-if="fileType === 'regional-screen' && getRegionalFiles.length !== 0">
				<div class="regional-screen-wrapper">
					<div class="regional-screen-video">
						<p class="regional-screen-text">区域录屏</p>
						<div class="regional-screen-video" v-for="(item, index) in getRegionalFiles" :key="index">
							<MarkerVideo :option="item" :videoConfig="videoConfig" :fileType="fileType" />
						</div>
					</div>
				</div>
			</template>
			<!-- 图片区域 -->
			<template v-if="fileType === 'picture'">
				<div :class="item.src ? 'img-border' : 'img-box'" v-for="item in imagesData" :key="item">
					<img v-if="item.src" :src="item.src" class="img-content" />
					<p v-else class="img-text">暂无图片</p>
					<p class="desc">{{ item.desc }}</p>
				</div>
			</template>
			<!-- 消息区域 -->
			<template v-if="fileType === 'message'">
				<div class="file-component-message-box">
					<TableComponent :tableData="messageData.list" @handleSelectionChange="handleSelectionChange" />
					<div class="page-size">
						<PageSize :pages="messagePages" @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
					</div>
				</div>
			</template>
			<!-- 业务区域 -->
			<template v-if="fileType === 'business'">
				<div class="business-box">
					<TableComponent :tableData="businessData.list" @handleSelectionChange="handleSelectionChange" />
					<div class="page-size">
						<PageSize :pages="businessPages" @changePageSize="changeBusinessPageSize" @changeCurrentPage="changeBusinessCurrentPage" />
					</div>
				</div>
			</template>
		</div>
	</div>
</template>

<script>
import MarkerVideo from '../MarkerVideo.vue';
import TableComponent from './TableComponent.vue';
import PageSize from '@/views/components/PageSize.vue';
import { saveAs } from 'file-saver';
import Down from '@/modules/Down.js';
import axios from 'axios';
import { setOperationLogFuntion } from '@/utils/tool.js';
export default {
	props: {
		title: {
			type: String,
			required: true,
			default: () => ''
		},
		fileType: {
			type: String,
			required: true,
			default: () => ''
		},
		filedata: {
			type: Array,
			required: true,
			default: () => []
		},
		options: {
			type: Array,
			required: true,
			default: () => []
		},
		messageData: {
			type: Object,
			required: true,
			default: () => {}
		},
		businessData: {
			type: Object,
			required: true,
			default: () => {}
		},
		imagesData: {
			type: Array,
			required: true,
			default: () => []
		},
		isDisable: {
			type: Boolean,
			required: true,
			default: () => false
		},
		messagePages: {
			type: Object,
			required: true,
			default: () => {}
		},
		businessPages: {
			type: Object,
			required: true,
			default: () => {}
		},
		recordingConfig: {
			type: Object,
			required: true,
			default: () => {}
		}
	},
	components: {
		MarkerVideo,
		TableComponent,
		PageSize
	},
	data() {
		return {
			videoConfig: {
				width: '352px',
				height: '232px'
			},
			recordData: {
				total: '',
				list: []
			},
			multipleSelection: [],
			searchKeyWord: '',
			screenType: '',
			isDownloadRecordFile: false // 是否正在下载录像文件
		};
	},
	computed: {
		// 系统录像数据
		getSystemRecordFiles() {
			// return this.options.filter(file => !file.userId && file.type === 'system');
			return this.options.filter(file => file.type === 'system');
		},
		// 坐席录屏数据
		getAgentRecordFiles() {
			console.log(this.options);
			return this.options.filter(file => file.userId && file.type === 'agent-screen');
		},
		// 区域录屏 数据
		getRegionalFiles() {
			console.log(this.options);
			return this.options.filter(file => file.userId && file.type === 'regional-screen');
		}
	},
	methods: {
		onClickDownload(fileType) {
			let filesCount = 0;
			let downloadedCount = 0;
			if (fileType === 'video' || fileType === 'agent-recorg') {
				console.log('下载录像文件');
				if(this.isDownloadRecordFile){
					return;
				}
				filesCount = this.filedata.length;
				for (let i = 0; i < this.filedata.length; i++) {
					let item = this.filedata[i];
					console.log(item);
					this.isDownloadRecordFile = true;
					this.downloadVideo(item.url, item.id, resp => {
						console.log('downloadVideo', resp);
						this.isDownloadRecordFile = false;
						if (resp.code === 200) {
							downloadedCount++;
						} else {
							this.$message.error('下载失败！');
						}
					});
				}
			} else if (fileType === 'picture') {
				console.log('下载通话随传资料');
				console.log(this.imagesData);
				filesCount = this.imagesData.length;
				for (let i = 0; i < this.imagesData.length; i++) {
					let item = this.imagesData[i];
					if (item.src.startsWith('http://')) {
						item.src = item.src.replace(/http/, 'https');
						console.log(item.src);
						saveAs(item.src, item.desc + '.png');
					} else {
						saveAs(item.src, item.desc + '.png');
					}
					downloadedCount++;
				}
				setOperationLogFuntion({ type: '1', category: 'downloadAndExport', content: '下载通话随传资料' });
			} else if (fileType === 'message') {
				console.log('下载聊天文件');
				console.log(this.multipleSelection);
				filesCount = this.multipleSelection.length;
				for (let i = 0; i < this.multipleSelection.length; i++) {
					let item = this.multipleSelection[i];
					// aws 存储的文件需要拼接url
					if(awsFileUrl){
						item.url = awsFileUrl + item.url;
					}
					console.log('item.url:', item.url);
					if (item.url.startsWith('http://')) {
						item.url = item.url.replace(/http/, 'https');
						console.log(item.url);
						saveAs(item.url, item.fileName);
					} else {
						saveAs(item.url, item.fileName);
					}
					downloadedCount++;
				}
				setOperationLogFuntion({ type: '1', category: 'downloadAndExport', content: '下载聊天文件' });
			} else {
				console.log('下载业务操作文件');
				console.log(this.multipleSelection);
				filesCount = this.multipleSelection.length;
				for (let i = 0; i < this.multipleSelection.length; i++) {
					let item = this.multipleSelection[i];
					// aws 存储的文件需要拼接url
					if(awsFileUrl){
						item.url = awsFileUrl + item.url;
					}
					console.log('item.url:', item.url);
					if (item.url.startsWith('http://')) {
						item.url = item.url.replace(/http/, 'https');
						console.log(item.url);
						saveAs(item.url, item.fileName);
					} else {
						saveAs(item.url, item.fileName);
					}
					downloadedCount++;
				}
				setOperationLogFuntion({ type: '1', category: 'downloadAndExport', content: '下载业务操作文件' });
			}

			// setTimeout(() => {
			// 	this.$message.success(`本次一共请求${filesCount}份文件，下载成功${downloadedCount}份，下载失败${filesCount - downloadedCount}份`);
			// }, 1000);
		},
		changePageSize(val) {
			this.$emit('changePageSize', val);
		},
		changeCurrentPage(val) {
			this.$emit('changeCurrentPage', val);
		},
		changeBusinessPageSize(val) {
			this.$emit('changeBusinessPageSize', val);
		},
		changeBusinessCurrentPage(val) {
			this.$emit('changeBusinessCurrentPage', val);
		},
		// 下载聊天文件类型和业务操作文件
		handleSelectionChange(val) {
			let result = [];
			val.forEach(item => {
				let obj = {};
				obj.fileName = item.fileName;
				obj.url = item.url;
				result.push(obj);
			});
			console.log(result);
			this.multipleSelection = result;
			console.log(this.isDisable);
			console.log(val);
			this.$emit('handleSelectionChange', result);
		},
		searchClick() {
			this.$emit('searchClick', this.searchKeyWord);
		},

		// 下载录像文件
		downloadVideo(url, id, callback) {
			let psize = 100 * 1024; // 100kb
			axios({
				url,
				method: 'GET',
				responseType: 'blob',
				headers: {
					Range: 'bytes=0-0'
				}
			})
				.then(response => {
					console.log('downloadVideo response', response);
					if (response.headers['content-range']) {
						this.$message.info('正在后台下载，请稍后查看');
						let fileData = {
							url: url,
							psize: psize,
							fileType: response.headers['content-type'],
							total: Number(response.headers['content-range'].split('/')[1]),
							id: id,
							fileName: '录像文件.mp4'
						};
						Down.startSize = 0;
						Down.download(fileData, e => {
							console.log(e);
							callback({ code: 400, data: e, message: 'download video failed' });
						},()=>{
							callback({ code: 200, data: response, message: 'download video success' })
						});
					} else {
						axios({
							url: url,
							method: 'GET',
							responseType: 'blob',
							headers: {
								'content-type': 'application/octet-stream'
							}
						})
							.then(resp => {
								console.log(resp);
								let fileURL = window.URL.createObjectURL(new Blob([resp.data]));
								let fileLink = document.createElement('a');
								fileLink.href = fileURL;
								fileLink.setAttribute('download', '录像文件.mp4');
								document.body.appendChild(fileLink);
								fileLink.click();
								callback({ code: 200, data: resp, message: 'download video success' });
							})
							.catch(e => {
								callback({ code: 400, data: e, message: 'download video failed' });
							});
					}
				})
				.catch(e => {
					callback({ code: 400, data: e, message: 'download video failed' });
				});
		}
	},
	mounted() {
		// console.log(this.multipleSelection);
		console.log('fileType', this.fileType);
		console.log(this.options, 'option');
	}
};
</script>

<style lang="less" scoped>
.file-componets-container {
	padding: 20px;
	.title {
		padding: 10px 0;
		font-size: 16px;
		font-family: PingFang SC;
		font-weight: 700;
		color: #333333;
		line-height: 24px;
	}
	.hr {
		color: #dedede;
		opacity: 0.3;
	}
	.header-box {
		padding: 20px 0 14px 10px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		.download-btn {
			background: #6384fe;
			border-radius: 4px;
			color: #fff;
		}
		.gray-btn {
			background: #e7e7e7;
			border: none;
			color: #fff;
		}
	}
	.content {
		display: flex;
		flex-wrap: wrap;
		padding-left: 10px;
		width: 100%;
		position: relative;
		.system-video {
			font-size: 13px;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #333333;
			position: absolute;
			top: -8px;
			left: 15px;
		}
		.video-box {
			padding: 20px 10px 10px 0px;
		}
		.agent-recorg-video {
			margin-top: -81px;
			// display: flex;
			// flex-wrap: wrap;

			.recording-screen {
				font-size: 13px;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #333333;
				position: absolute;
				top: -98px;
				left: 8px;
			}
			.seat-recording-video {
				margin-top: 10px;
				padding: 0px 20px 10px 0px;
				// margin-bottom: 100px;
				height: 242px;
				min-height: 242px;
				box-sizing: border-box;

				.mark-video-main {
					height: 232px;
					min-height: 232px;
				}
			}
			.seat-recording-video-wrapper {
				display: flex;
				flex-wrap: wrap;
				height: fit-content;
			}
		}
		.regional-screen-wrapper {
			margin-top: -100px;
			.regional-screen-video {
				margin-top: 20px;
				display: flex;
				flex-wrap: wrap;

				.regional-screen-text {
					font-size: 13px;
					font-family: PingFangSC-Regular, PingFang SC;
					font-weight: 400;
					color: #333333;
					position: absolute;
					top: -95px;
					left: 8px;
				}
				.regional-screen-video {
					// margin-top: -130px;
					padding: 0px 20px 10px 0px;
					// margin-bottom: 100px;
				}
			}
		}
		.img-box {
			cursor: pointer;
			position: relative;
			margin-right: 20px;
			width: 188px;
			height: 118px;
			background-color: #fbfbfb;
			border: 2px dashed #d7d7d9;
			.img-text {
				text-align: center;
				line-height: 118px;
				color: #ccc;
			}
		}
		.img-content {
			width: 190px;
			height: 153px;
		}
		.img-border {
			cursor: pointer;
			position: relative;
			margin-right: 20px;
			width: 188px;
			height: 118px;
			background-color: #fbfbfb;
			border: none;
			.img-text {
				text-align: center;
				line-height: 118px;
				color: #ccc;
			}
			.desc {
				position: absolute;
				text-align: center;
				transform: translate(-50%, 50%);
				left: 50%;
				bottom: -50%;
				color: #666;
			}
		}
		.desc {
			position: absolute;
			text-align: center;
			transform: translate(-50%, 50%);
			left: 50%;
			bottom: -20%;
			color: #666;
		}
		.file-component-message-box,
		.business-box {
			width: 100%;
		}
		.page-size {
			padding: 20px 0;
		}
		.videoFile-box {
			width: 295px;
			height: 150px;
			margin: auto 80px;
			.title {
				font-size: 12px;
				font-family: PingFang SC;
				font-weight: 400;
				color: #333333;
			}
			.paddingTop {
				padding-top: 10px;
			}
		}
	}
	.el-input {
		width: 310px;
	}
}
</style>
